// pages/reviewRecord/wordReadWord/wordReadWord.js
const app = getApp();
let tool = require('../../../utils/tool.js');
const httpUtils = require('../../../utils/httpUtils.js');
let util = require('../../../utils/util.js');
const audio = require('../../../utils/audioword.js');
const log = require('../../../utils/log.js')
import Dialog from '../../../dist/dialog/dialog';
//  正在录音的下标
let recordingIndex = 0;


Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageurl: app.globalData.imageurl,
    okNums: 0,
    errNums: 0,
    selNums: {},
    ansNums: {},
    reviewNum: 0, //今日有多少词需复习
    // flag: true, //显示隐藏提示复习的弹窗的标志
    innerAudioContext: new Object(),
    allWord: '',
    errWord: '',
    canClick: 0,
    questData: [],
    wordID: 0,
    wordLen: 0,
    readTimes: {},
    page: 1,
    pageSize: 50,
    hasMoreData: false,
    isFirst: true,
    reviewTime: "19:00", //复习推送时间
    reviewStatus: "1", //复习状态 0 复习完成可查看错词；1有复习单词；2 今日无复习任务；3未到复习时间
    has_review: 0, //0未复习  1已复习
    has_read: 1, //0无语音识别读一遍，1有读一遍
    has_picture: 0, //0无图片作业   1有图片作业
    fileList: [], //上传图片列表
    btnPlayStatus: [], //语音识别的三个按钮的状态
    showRecordModal: false, //正在识别的弹窗
    originalStr: "", //原字符串即单词（打分时用）
    task_id: '', //任务id
    sort: '5', //作业形式 1 词义闯关 2 对对碰 3 廷议释义 4 组合拼 5读一遍 6 写一遍
    cloudPath: [],
    tempFiles: "",
    isUploadComplet: 0, //0图片未上传完，1已上传完
    userAnswerList: [], //对应学生答案（stu_answer json数据）
    can_submit: 1, //1 可以提交 0不可以提交
    pic: [], //图片作业数组
    status: 0, //0未复习 1未完成 2已复习
    flag: true, //是否显示提交成功的弹窗
    hasReadNum: 0, //已录音多少个单词
    isScoreing: 0, //0打分弹窗关闭， 1 正在打分的弹窗
    referBtnText: '下一页', //一页返回50个，如果还有下页数据就显示下一页，没有下页数据就显示提交
    isFirstList: false, //是否是第一次请求数据，只有第一次初始化总数

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    this.data.innerAudioContext = wx.createInnerAudioContext()
    this.data.innerAudioContext.autoplay = false;
    this.data.innerAudioContext.loop = false;
    //获取传过来需复习的单词数
    that.setData({
      task_id: options.task_id,
      sort: options.sort,
      can_submit: options.can_submit,
      status: options.status
    })
    console.log("接收到的sort=" + that.data.sort + "接收到的can_submit=" + that.data.can_submit + "status=" + that.data.status);
    if (that.data.sort == 5) {
      //读一遍
      that.setData({
        has_read: 1, //0无语音识别读一遍，1有读一遍
        has_picture: 0,
      })
      console.log("showRecordModal=" + that.data.showRecordModal)
    } else if (that.data.sort == 6) {
      // 写一遍
      that.setData({
        has_read: 0, //0无语音识别读一遍，1有读一遍
        has_picture: 1,
      })
    }

    // //获取今日单词复习数据
    this.getTodayReviewWord();

  },
  /**
   * 获取今日复习的单词 --- 重新调新的接口
   */
  getTodayReviewWord: function () {
    var that = this;
    that.setData({
      userAnswerList: []
    })
    wx.showLoading({
      title: '正在加载',
      mask: true
    })
    httpUtils.getWordReviewTask({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.task_id,
      sort: that.data.sort,
      page: that.data.page,
      size: that.data.pageSize
    }).then((res) => {
      if (!that.data.isFirstList) {
        that.setData({
          reviewNum: res.data.all_num,
          isFirstList: true,
          pic: res.data.pic
        })
      }
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
      var questData = that.data.questData;
      var list = res.data.lists;

      if (res.data.all_num < that.data.pageSize) {
        that.setData({
          questData: res.data.lists,
          hasMoreData: false,
          referBtnText: "提交"
        })
      } else {
        that.setData({
          questData: res.data.lists,
          hasMoreData: true,
          referBtnText: "下一页"
        })
      }

      let len = that.data.questData.length;
      that.setData({
        btnPlayStatus: audio.initAudioBtn(len, len)
      })
      audio.onEnded({
        callback(data) {
          that.setData({
            btnPlayStatus: data
          })
        }
      });
    });
  },

  //点击单词文本时
  clickTxt: function (event) {
    var that = this;
    let showRecordModal = that.data.showRecordModal;
    let temWrod = event.currentTarget.dataset.words;
    let temNum = that.data.selNums;

    console.log("showRecordModal=" + showRecordModal)
    if (showRecordModal) {
      console.log("正在录音...");
      return;
    }

    var isHas = false; //是否点击过 false没有点击过
    for (var key in temNum) { //0正常样式1英文变粗 2英文变粗出中文
      if (key == temWrod) {
        if (temNum[key] < 2) {
          temNum[key]++;
        } else {
          temNum[key] = 1;
        }
        isHas = true;
      } else {
        temNum[key] = 0;
      }
    }
    if (!isHas) {
      temNum[temWrod] = 1;
    }
    this.setData({
      selNums: temNum,
    });

    if (that.data.sort == 5) {
      //读一遍
      that.playAudio(event);
    } else if (that.data.sort == 6) {
      //写一遍
      that.data.innerAudioContext.stop();
      let audios = event.currentTarget.dataset.audiosrc;
      that.data.innerAudioContext.src = audios;
      that.data.innerAudioContext.play();
    }
  },

  // 播放音频
  playAudio: function (event) {
    var that = this;
    var type = event.currentTarget.dataset.type;
    var index = event.currentTarget.dataset.index;
    console.log("type=" + type + ",index=" + index)

    audio.play({
      type: type,
      index: index,
      audiosrc: event.currentTarget.dataset.audiosrc,
      callback(data) {
        that.setData({
          btnPlayStatus: data,
        });
      }
    });
  },

  //默认无录音时点击灰色播放读音按钮
  recordDisabled() {
    setTimeout(function () {
      wx.showToast({
        title: '请先录音~',
        icon: 'none',
        duration: 2000
      });
    }, 500)
  },

  //  录音并打分
  // recordScore: function (event) {
  recordScore: util.throttle(function (event) {
    var that = this;
    that.data.innerAudioContext.stop();
    recordingIndex = event.currentTarget.dataset.index;
    let origStr = event.currentTarget.dataset.originalstr;
    that.setData({
      showRecordModal: true,
      originalStr: that.replaceStr(origStr)
    });
    console.log("originalStr:" + that.data.originalStr)

    audio.stop({
      callback(data) {
        that.setData({
          btnPlayStatus: data,
        });
      }
    });

  }, 1000),

  //替换字符串
  replaceStr(str) {
    let newstr = str.replace(/sb./g, 'somebody').replace(/sth./g, 'something').replace(/sw./g, 'somewhere');
    return newstr;
  },



  //点击录音弹窗中的完成按钮，关闭弹窗
  modalFinish: util.throttle(function () {
    let that = this;
    that.setData({
      showRecordModal: false,
      isScoreing: 1,
    });
    console.log("关闭了录音弹窗,显示打分loading")
    wx.showLoading({
      title: '正在打分...',
      mask: true
    })
  }, 2000),

  //录音失败
  recordFail: function (res) {
    console.log("wordwork界面recordFail")
    let that = this;
    if (that.data.showRecordModal) {
      console.log("设置弹窗状态隐藏false")
      that.setData({
        showRecordModal: false,
      });
    }
    setTimeout(function () {
      wx.hideLoading({
        success: (res) => {
          that.setData({
            isScoreing: 0,
          })
        },
      })
    }, 100)
  },

  // 录音成功
  recordSuccess: function (res) {
    var that = this;
    console.log("wordwork界面录音成功")
    setTimeout(function () {
      wx.hideLoading()
    }, 100)
    that.setData({
      isScoreing: 0,
    })

    if (that.data.showRecordModal) {
      that.setData({
        showRecordModal: false,
      });
      console.log("recordSucc--onstop--设置弹窗为false")
    }



    let score = res.detail.score;
    console.log("score=" + score)
    let tempFilePath = res.detail.tempFilePath;
    if (score == 0) {
      setTimeout(function () {
        wx.showToast({
          title: '没有听清,请放慢速度再读一遍~',
          icon: 'none',
          duration: 2000
        });
      }, 800)
    }

    let questData = that.data.questData;
    let hasReadNum = that.data.hasReadNum;
    if (questData[recordingIndex].score < 0) {
      that.setData({
        hasReadNum: hasReadNum + 1,
      })
    }
    questData[recordingIndex].score = score;
    questData[recordingIndex].user_per_voice = tempFilePath;
    that.setData({
      questData: questData
    })

    let bodyParam = {
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      type: tempFilePath,
    }
    let rs = tool.getSign(bodyParam, getApp().globalData.key);
    let tempurl = getApp().globalData.apiURL + 'common/upload?sign=' + rs.sign;
    console.log(tempurl)
    wx.uploadFile({
      url: tempurl,
      filePath: tempFilePath,
      name: 'file',
      formData: {
        'word': that.data.questData[recordingIndex].word,
        'sub_vedio': tempFilePath,
        'type': 'wx_voice',
      },
      success(res) {
        console.log("录音上传成功res=" + res.data)
        let result = JSON.parse(res.data);
        let path = result.data.path;
        console.log("path=" + path)
        let userAnswerList = that.data.userAnswerList;
        let uanswer = new Object();
        uanswer['word'] = that.data.questData[recordingIndex].word;
        uanswer['voice'] = path;
        uanswer['score'] = score;
        userAnswerList.push(uanswer);
        that.setData({
          userAnswerList: userAnswerList
        })

      },
    })

  },


  // 上传文件后
  afterRead(event) {
    let that = this;
    let fileList = that.data.fileList;
    const {
      file
    } = event.detail;
    console.log(file)
    that.setData({
      fileList: fileList.concat(file)
    })

    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    //上传文件
    var successUp = 0; //成功个数
    var failUp = 0; //失败个数
    var length = file.length; //总共个数
    var i = 0; //第几个
    console.log("that.data.fileList.length=" + length)
    that.uploadFilePromise(file, successUp, failUp, i, length);
  },

  uploadFilePromise(filePaths, successUp, failUp, i, length) {
    let that = this;
    let cloudPath = that.data.cloudPath;
    wx.showLoading({
      title: '正在上传',
      mask: true
    })
    let bodyParam = {
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      type: filePaths[i].path,
    }
    let rs = tool.getSign(bodyParam, getApp().globalData.key);
    let tempurl = getApp().globalData.apiURL + 'common/upload?sign=' + rs.sign;
    console.log("tempurl:" + tempurl)
    return wx.uploadFile({
      url: tempurl,
      filePath: filePaths[i].path,
      name: 'file',
      formData: {
        'type': filePaths[i].path,
      },
      success(res) {
        successUp++;
        let result = JSON.parse(res.data);
        console.log("图片上传成功result=" + res.data);
        cloudPath.push(result.data.path);
      },
      fail(res) {
        failUp++;
      },
      complete: () => {
        wx.hideLoading();
        i++;
        if (i == length) {
          // that.showToast('总共'+successUp+'张上传成功,'+failUp+'张上传失败！');

          console.log('总共' + successUp + '张上传成功,' + failUp + '张上传失败！');
          wx.showToast({
            title: '图片上传成功~',
            icon: 'none',
            duration: 2000
          });
          that.setData({
            isUploadComplet: 1,
          })
        } else { //递归调用upload函数
          that.uploadFilePromise(filePaths, successUp, failUp, i, length);
        }
      },
    })
  },


  //删除上传的图片
  deleteimg(event) {
    let that = this;
    const {
      index
    } = event.detail;
    let fileList = that.data.fileList;
    let cloudPath = that.data.cloudPath;
    fileList.splice(index, 1);
    cloudPath.splice(index, 1);
    that.setData({
      fileList: fileList,
      cloudPath: cloudPath
    });
  },

  //提交复习
  gotourl: util.throttle(function () {
    let that = this;
    let answerList = that.data.userAnswerList;
    if (that.data.has_picture == 1) {
      let fileList = that.data.fileList;
      if (!fileList.length) {
        wx.showToast({
          title: '请先上传作业图片',
          icon: 'none',
          duration: 1000
        })
        return;
      } else {
        let cloudPath = that.data.cloudPath;
        let tempFiles = '';
        for (var i = 0; i < cloudPath.length; i++) {
          if (tempFiles == '') {
            tempFiles = cloudPath[i];
          } else {
            tempFiles = tempFiles + "," + cloudPath[i];
          }
        }
        console.log("tempFiles=" + tempFiles)
        that.setData({
          tempFiles: tempFiles
        })
      }

    } else {
      log.info('wordreadone,click submit button')
      console.log('=====wordreadone,click submit button,isScoreing=' + that.data.isScoreing)
      if (that.data.isScoreing == 1) {
        console.log("---正在打分，关闭打分弹窗---")
        wx.hideLoading();
      }
      if (that.data.showRecordModal) {
        wx.showToast({
          title: '请先完成录音后再提交',
          icon: 'none',
          duration: 2000
        })
        console.log("正在录音")
        log.warn("正在录音")
        return;
      }


      if (answerList.length <= 0) {
        wx.showToast({
          title: '请先点击单词条目录音',
          icon: 'none',
          duration: 2000
        })
        console.log("answerList为空，需先录音")
        log.warn('answerList为空，需先录音')
        return;
      }
    }

    if (answerList.length < that.data.questData.length) {
      wx.showToast({
        title: '请先完成本页所有作业',
        icon: 'none',
        duration: 2000
      })
    } else {
      if (that.data.hasMoreData) {
        that.submitAnswer();
      } else { //最后一页
        wx.showModal({
          title: '提示',
          content: '是否确认提交',
          success(res) {
            if (res.confirm) {
              that.setData({
                showRecordModal: false
              })
              log.info("confirm，调提交接口")
              that.submitAnswer();
            } else if (res.cancel) {
              log.info("点击了取消提交")
            }
          }
        })
      }
    }

  }, 2000),


  submitAnswer() {
    let that = this;
    let answerList = that.data.userAnswerList;
    wx.showLoading({
      title: '正在提交',
      mask: true
    })
    httpUtils.submitWordReview({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.task_id,
      sort: that.data.sort,
      pic: that.data.tempFiles,
      stu_answer: JSON.stringify(answerList),
      errword: "",
      allword: "",
    }).then((res) => {
      wx.hideLoading();
      //弹提交成功的弹窗
      if (that.data.hasMoreData) {
        that.getTodayReviewWord()
      } else {
        that.setData({
          flag: false
        })
      }

    });
  },

  //点击弹窗中的完成按钮
  goComplet() {
    wx.navigateBack({
      delta: -1
    })
  },


  //点击查看大图
  lookBigPic(e) {
    console.log("lookbigpic" + JSON.stringify(e))
    let that = this;
    let index = e.currentTarget.dataset.index;
    let imgUrl = that.data.pic;
    let currenturl = imgUrl[index];
    //在新界面预览样例大图
    wx.previewImage({
      current: currenturl,
      urls: imgUrl,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //停止播放
    let that = this;
    console.log("wordwork界面onHide")
    that.data.innerAudioContext.stop();
    audio.destory();
    that.setData({
      showRecordModal: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this;
    console.log("wordwork界面onUnload")
    audio.destory();
    that.data.innerAudioContext.stop();
    that.data.innerAudioContext.destroy();
    that.setData({
      showRecordModal: false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // var that = this;
    // console.log("当前页:", that.data.page)

    // if (that.data.hasMoreData) {
    //   console.log("获取更多数据")
    //   that.getTodayReviewWord();
    // } else {
    //   wx.showToast({
    //     title: '没有更多数据了',
    //     icon: 'none'
    //   })
    // }

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})